/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unice.miage.oobdoo.servlet;

import com.unice.miage.oobdoo.Config;
import com.unice.miage.oobdoo.entity.Commentaire;
import com.unice.miage.oobdoo.entity.Photo;
import com.unice.miage.oobdoo.entity.Utilisateur;
import com.unice.miage.oobdoo.helpfull.EmailSender;
import com.unice.miage.oobdoo.manager.CommentaireManager;
import com.unice.miage.oobdoo.manager.PhotoManager;
import com.unice.miage.oobdoo.manager.UtilisateurManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Jeremy Romano
 */
public class CommentaireServlet extends HttpServlet {

    @EJB
    UtilisateurManager utilisateurManager;
    @EJB
    PhotoManager photoManager;
    @EJB
    CommentaireManager commentaireManager;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");

        if (action != null) {
            if (action.equals("add")) {
                String commentaire = ((String) request.getParameter("commentaire")).replaceAll("\n", "<br/>");
                String idPhoto = (String) request.getParameter("idPhoto");

                HttpSession session = request.getSession(true);
                String id = session.getAttribute("id").toString();

                Utilisateur auteur = utilisateurManager.getUtilisateurById(Integer.valueOf(id));
                Photo photo = photoManager.getPhotoById(Integer.valueOf(idPhoto));

                Commentaire c = commentaireManager.creerCommentaire(auteur, photo, commentaire);
                photoManager.addCommentaire(photo, c);

                // ET SI ON ENVOYAIS UN MAIL ;)
                if (c.getAuteur().getId() != photo.getAlbum().getAuteur().getId()) {
                    final EmailSender emailer = new EmailSender();

                    final String to = photo.getAlbum().getAuteur().getEmail();

                    final String subject = "Nouveau Commentaire de " + auteur.getLogin();
                    final String message = "Nouveau commentaire sur la photo " + photo.getNom() + "<br />"
                                    + "<p>" + c.getTexte() + "</p><br /><br />"
                                    + "<a href=" + Config.WEBURL + "'/PhotoServlet?action=view&IdPhoto=" + photo.getId() + "'>Cliquer ici pour visualiser</a>";

                    Thread t = new Thread(){
                        @Override
                        public void run()
                        {
                            try{
                                emailer.sendEmail( subject,
                                    message,
                                    to);
                            }
                            catch(Exception ex)
                            {
                                System.out.println("ex = " + ex.getMessage());
                            }
                        }
                    };
                    t.start();


                    
                }
                //RENVOIE LA REPONSE EN JSON
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.println("{\"ret\":\"1\", \"login\":\""
                        + auteur.getLogin()
                        + "\",\"idAuteurPhoto\":\""
                        + photo.getAlbum().getAuteur().getId()
                        + "\",\"idAlbum\":\""
                        + photo.getAlbum().getId()
                        + "\",\"thumb\":\""
                        + photo.getPathThumbHome()
                        + "\",\"commentaire\":\""
                        + commentaire
                        + "\",\"date\":\""
                        + c.getCreationToString()
                        + "\",\"nbCommentaires\":\""
                        + photo.getCommentaires().size()
                        + "\"}");
            } else if (action.equals("allNotifications")) {
                HttpSession session = request.getSession(true);
                String id = session.getAttribute("id").toString();

                Utilisateur auteur = utilisateurManager.getUtilisateurById(Integer.valueOf(id));
                Collection<Commentaire> com = commentaireManager.getCommentaire(auteur);

                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                /*
                 * {
                 *  "ret":"1",
                 *  "commentaires":
                 *  [
                 *      {
                 *          "auteur": "",
                 *          "vue", "",
                 *          "texte": "",
                 *          "idPhoto": "",
                 *          "nomPhoto": "",
                 *          "thumb": ""
                 *      },
                 *      {
                 *          ...
                 *      }
                 *      ...
                 *  ]
                 * }
                 */
                String json = "{\"ret\":\"1\",\"commentaires\":[";
                for (Commentaire c : com) {
                    json += "{";
                    json += "\"auteur\":";
                    json += "\"" + c.getAuteur().getLogin() + "\",";
                    json += "\"vue\":";
                    json += "\"" + c.isVue() + "\",";
                    json += "\"texte\":";
                    json += "\"" + c.getTexteCompact() + "\",";
                    json += "\"idPhoto\":";
                    json += "\"" + c.getPhoto().getId() + "\",";
                    json += "\"nomPhoto\":";
                    json += "\"" + c.getPhoto().getNom() + "\",";
                    json += "\"thumb\":";
                    json += "\"upload/" + c.getPhoto().getAlbum().getAuteur().getId() + "/" + c.getPhoto().getAlbum().getId() + "/" + c.getPhoto().getPathThumbHome() + "\"";
                    json += "},";
                }
                json += "]}";
                out.println(json);
            } else if (action.equals("notifications")) {
                HttpSession session = request.getSession(true);
                String id = session.getAttribute("id").toString();

                Utilisateur auteur = utilisateurManager.getUtilisateurById(Integer.valueOf(id));
                Collection<Commentaire> com = commentaireManager.getCommentaireNotVue(auteur);

                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                /*
                 * {
                 *  "ret":"1",
                 *  "nb":"",
                 *  "commentaires":
                 *  [
                 *      {
                 *          "auteur": "",
                 *          "vue": "",
                 *          "texte": "",
                 *          "idPhoto": "",
                 *          "nomPhoto": "",
                 *          "thumb": ""
                 *      },
                 *      {
                 *          ...
                 *      }
                 *      ...
                 *  ]
                 * }
                 */
                String json = "{\"ret\":\"1\""
                        + ",\"nb\":\"" + commentaireManager.getCommentaire(auteur).size() + "\""
                        + ",\"commentaires\":[";
                
                int i = 0;
                
                for (Commentaire c : com) {
                    json += "{";
                    json += "\"auteur\":";
                    json += "\"" + c.getAuteur().getLogin() + "\",";
                    json += "\"vue\":";
                    json += "\"" + c.isVue() + "\",";
                    json += "\"texte\":";
                    json += "\"" + c.getTexteCompact() + "\",";
                    json += "\"idPhoto\":";
                    json += "\"" + c.getPhoto().getId() + "\",";
                    json += "\"nomPhoto\":";
                    json += "\"" + c.getPhoto().getNom() + "\",";
                    json += "\"thumb\":";
                    json += "\"upload/" + c.getPhoto().getAlbum().getAuteur().getId() + "/" + c.getPhoto().getAlbum().getId() + "/" + c.getPhoto().getPathThumbHome() + "\"";
                    if( i >= com.size()-1)
                    {
                        json += "}";
                    }
                    else
                    {
                        json += "},";
                    }
                    i++;
                }
                
                json += "]}";
                out.println(json);
            } else if (action.equals("nbNotifications")) {
                HttpSession session = request.getSession(true);
                String id = session.getAttribute("id").toString();

                Utilisateur auteur = utilisateurManager.getUtilisateurById(Integer.valueOf(id));
                Collection<Commentaire> com = commentaireManager.getCommentaireNotVue(auteur);

                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();

                int nbCommentaires = 0;

                if (com != null) {
                    nbCommentaires = com.size();
                }

                /*
                 * {"ret":"1","commentaires":""}
                 */
                String json = "{\"ret\":\"1\",\"commentaires\":\"" + nbCommentaires + "\"}";
                out.println(json);
            } else {
                String forwardTo = "AlbumServlet?action=list";

                if (action.equals("viewNew")) {
                    String firstString = request.getParameter("first");
                    String maxString = request.getParameter("max");
                    int first = 0;
                    int max = 10;
                    if (firstString != null) {
                        first = Integer.valueOf(firstString);
                    }
                    if (maxString != null) {
                        max = Integer.valueOf(maxString);
                    }

                    System.out.println("max=" + max);
                    System.out.println("maxString=" + maxString);

                    HttpSession session = request.getSession(true);
                    String id = session.getAttribute("id").toString();

                    Utilisateur auteur = utilisateurManager.getUtilisateurById(Integer.valueOf(id));
                    Collection<Commentaire> com;
                    if (first < 0 || max <= 0) {
                        com = commentaireManager.getCommentaire(auteur);
                    } else {
                        com = commentaireManager.getCommentaire(auteur, first, max);
                    }

                    request.setAttribute("commentaires", com);
                    request.setAttribute("nbCommentaires", commentaireManager.getCommentaire(auteur).size());

                    Collection<Commentaire> comNotVue = commentaireManager.getCommentaireNotVue(auteur);
                    for (Commentaire c : comNotVue) {
                        commentaireManager.updateViewCommentaire(c, true);
                    }

                    forwardTo = "notifications/commentaires.jsp";
                }

                RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                dp.forward(request, response);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
